<?php

namespace common\components;

use common\messages\ErrorCode;
use Yii;
use yii\base\UserException;

/**
 * Exception Model
 * 异常 模型
 */
class Exception extends UserException
{
    const ERROR = 'error';
    const DEFAULT_ERROR = 'UNKNOWN_ERROR';

    /**
     * 构造函数
     * -----------------------------------------
     * @param Integer / String $code 错误代码
     * @param String / Integer $message 错误描述
     * @param Throwable $previous 先前的Exception
     * ------------------------------------------
     * @inheritdoc
     */
    public function __construct($code = null, $validError = false, $previous = null)
    {
        if ($validError) {
            $message = $code;
            $code = 422;
        } else {
            $message = Yii::t('codeMsg', $code);
            $errorCode = ErrorCode::CODE;
            $errorCode = array_flip($errorCode);
            isset($errorCode[$code]) ? $code = $errorCode[$code] : $code = $errorCode[self::DEFAULT_ERROR];
            $code == $errorCode[self::DEFAULT_ERROR] && $message = Yii::t('codeMsg', self::DEFAULT_ERROR);
        }
        parent::__construct($message, (int)$code, $previous);
    }

    /**
     * getName()
     * 获取异常信息
     * @inheritdoc
     * @return String
     */
    public function getName()
    {
        return self::ERROR;
    }
}
